package at.ttasat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class Util {
	public static String combineParameters(String[] args) {
		StringBuilder parameters = new StringBuilder();
		for (int i = 0; i < args.length; i++) {
			boolean containsSpace = args[i].contains(" ");
			if(containsSpace) parameters.append("\"");
			parameters.append(args[i]);
			if(containsSpace) parameters.append("\"");
			parameters.append(' ');
		}
		return parameters.toString().trim();
	}

	public static TasatType getTasatType(String typeString) {
		if (typeString.equals("t")) {
			return TasatType.Tasat;
		} else if (typeString.equals("p")) {
			return TasatType.P_Tasat;
		} else if (typeString.equals("l")) {
			return TasatType.L_Tasat;
		} else
			throw new IllegalArgumentException("Tasat type");
	}

	public static void save(SolverTestResult result, String fileName) throws FileNotFoundException, IOException {
		fileName = getFileName(result, fileName);

		System.out.println("Writing result to :" + fileName);
		FileOutputStream outputStream = new FileOutputStream(fileName);
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
		objectOutputStream.writeObject(result);
		objectOutputStream.close();
	}

	public static String getFileName(SolverTestResult result, String fileName) {
		DateFormat format = new SimpleDateFormat("YYYY_MM_dd_HH_mm_ss");
		fileName = fileName.replace("{d}", format.format(result.getDate()));
		fileName = fileName.replace("{t}", getTasatTypeString(result.getTasatType()));
		fileName = fileName.replace("{c}", result.getComputerName());
		fileName = fileName.replace("{p}", result.getParameters().replaceAll("[:\\\\/*?|<>]", "_").replace("\"", ""));
		return fileName;
	}

	public static String getTasatTypeString(TasatType tasatType) {
		switch (tasatType) {
		case Tasat:
			return "Normal";
		case P_Tasat:
			return "Parallel";
		case L_Tasat:
			return "Learning";
		}
		throw new IllegalArgumentException();
	}

	public static SolverTestResult readTestResult(String fileName) throws FileNotFoundException, IOException, ClassNotFoundException {
		return readTestResult(new File(fileName));
	}

	public static SolverTestResult readTestResult(File file) throws FileNotFoundException, IOException, ClassNotFoundException {
		FileInputStream inputStream = new FileInputStream(file);
		ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
		SolverTestResult comparisonResult = (SolverTestResult) objectInputStream.readObject();
		objectInputStream.close();
		return comparisonResult;
	}
}
